#include <QVariant>
#include <QWidget>

#include "SequencePainter.h"
#include "sequenceitem.h"
#include "ApplicationIcon.h"


#define SMALL_ICON_SIZE    20  /**< icon for sequence items are 20x20 */
#define INFINITE_SYMBOL    QChar(0x221E)


SequencePainter::SequencePainter() :
   ActionListPainter()
{
   m_penForItemNumber = new QPen( QColor(200, 0, 0));
}

SequencePainter::~SequencePainter()
{
   delete m_penForItemNumber;
}

void SequencePainter::paintItem(const QRect &draw_area, const QVariant &displayData, int position)
{
   const SequenceItem *item = displayData.value< const SequenceItem *>();
   Q_ASSERT( item != NULL);

   QString delay = delayString( item);
   QPixmap icon = itemPixmap( item);
   QString index = QString("(%1) ").arg(position + 1);
   QString indexOfNext = nextItemString( item);

   QPainter *painter = this->painter();

   int indexWidth = painter->fontMetrics().width( index);
   int indexOfNextWidht = painter->fontMetrics().width( indexOfNext);

   painter->drawPixmap( draw_area.topLeft(), icon);

   QTextOption txt_opt;
   txt_opt.setWrapMode( QTextOption::NoWrap );

   painter->setPen( *m_penForItemNumber);
   painter->drawText( draw_area.adjusted( SMALL_ICON_SIZE, 0,0,0),
                        index, txt_opt );

   painter->setPen( targetWidget()->palette().foreground().color());

   painter->drawText( draw_area.adjusted( SMALL_ICON_SIZE + indexWidth, 0, -indexOfNextWidht, 0),
                        QString("%1 - [%2]").arg(item->label()).arg(delay), txt_opt );

   painter->setPen( *m_penForItemNumber);
   txt_opt.setAlignment( Qt::AlignRight);
   painter->drawText( draw_area, QString("%1").arg(indexOfNext), txt_opt );
}

/**
 * format the string to print delay from previous item for
 * given \p item
 */
QString SequencePainter::delayString(const SequenceItem *item)
{
   QString delay;

   if (item->delayMs() == SequenceItem::DELAY_INFINITE)
   {
      delay = QString("%1").arg(INFINITE_SYMBOL);
   }
   else
   {
      delay = QString("%1 s").arg( (double)(item->delayMs())/1000., 2 );
   }

   return delay;
}

QPixmap SequencePainter::itemPixmap(const SequenceItem *item)
{
   QPixmap icon;

   if (item->type() == SequenceItem::TRACK)
   {
      icon.load(IconPath("sound-small.png"));
   }
   else if (item->type() == SequenceItem::LIGHT)
   {
      icon.load(IconPath("light-small.png"));
   }

   return icon;
}

QString SequencePainter::nextItemString(const SequenceItem *item)
{
   QString nextIndex;

   if (item->indexOfNext() != SequenceItem::NEXT_IS_UNDEFINED)
   {
      nextIndex = QString("  >> (%1)  ").arg(item->indexOfNext() + 1);
   }

   return nextIndex;
}
